<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" v-auth="'warehouse:wms_storage_locations:add'" @click="handleAdd"
          preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button type="primary" v-auth="'warehouse:wms_storage_locations:exportXls'"
          preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button type="primary" v-auth="'warehouse:wms_storage_locations:importExcel'"
          preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>

        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
              <a-menu-item key="2" @click="batchEnable">
                <Icon icon="ant-design:check-circle-outlined"></Icon>
                启用
              </a-menu-item>
              <a-menu-item key="3" @click="batchDisable">
                <Icon icon="ant-design:stop-outlined"></Icon>
                禁用
              </a-menu-item>
            </a-menu>
          </template>
          <a-button v-auth="'warehouse:wms_storage_locations:deleteBatch'">批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>

        <!-- 高级查询 -->
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
      </template>

      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>

      <!--字段回显插槽 (如果需要自定义显示，可以在这里添加) -->
      <template v-slot:bodyCell="{ column, record, index, text }">
        <!-- 示例：如果需要自定义某个字段的显示 -->
        <!--
        <template v-if="column.dataIndex === 'someField'">
          {{ yourCustomFormatFunction(text) }}
        </template>
        -->
      </template>
    </BasicTable>

    <!-- 表单区域 (模态框) -->
    <BasicModal
      v-bind="modalProps"
      @register="registerModal"
      @ok="handleSubmit"
      @cancel="closeModal"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>

<script lang="ts" name="warehouse-wmsStorageLocations" setup>
import { ref, reactive, computed, unref } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { BasicModal, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form';
import { useListPage } from '/@/hooks/system/useListPage'
import { columns, searchFormSchema, superQuerySchema, formSchema } from './WmsStorageLocations.data';
import {
  list,
  deleteOne,
  batchDelete,
  getImportUrl,
  getExportUrl,
  enableLocation,
  disableLocation,
  saveOrUpdate // 引入保存/更新 API
} from './WmsStorageLocations.api';
import { downloadFile } from '/@/utils/common/renderUtils';
import { useUserStore } from '/@/store/modules/user';
import { list as storageZonesList } from "@/views/warehouse/WmsStorageZones.api"; // 引入库区列表 API

const queryParam = reactive<any>({});
const checkedKeys = ref<Array<string | number>>([]);
const userStore = useUserStore();

// --- 模态框和表单逻辑 ---
const isUpdate = ref(true);
// Emits声明 (如果需要从子组件触发事件)
// const emit = defineEmits(['success']); 
// 如果父组件需要监听 success 事件，可以在 <WmsStorageLocationsModal> 上加 @success="handleSuccess"
// 但通常 useModalInner 内部处理即可

// 表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate, scrollToField, updateSchema }] = useForm({
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 12 }
});

// 模态框配置
const modalProps = ref({
  title: '操作',
  width: '50%',
  confirmLoading: false,
  showCancelBtn: true,
  showOkBtn: true,
});

// 注册模态框内部逻辑
const [registerModal, { openModal, setModalProps, closeModal }] = useModal();

// 表单赋值和模态框初始化
const initModal = async (data) => {
  // 重置表单
  await resetFields();
  // 设置模态框属性
  const showFooter = !!data?.showFooter;
  setModalProps({
    confirmLoading: false,
    showCancelBtn: showFooter,
    showOkBtn: showFooter,
    title: data?.isUpdate ? '编辑' : '新增'
  });
  
  isUpdate.value = !!data?.isUpdate;
  // isDetail.value = !!data?.showFooter; // 如果需要区分详情模式

  if (unref(isUpdate) && data.record) {
    // 表单赋值
    await setFieldsValue({
      ...data.record,
    });

    // --- 动态加载库区选项 ---
    const warehouseId = data.record.warehouseId;
    if (warehouseId) {
      try {
        const res = await storageZonesList({ warehouseId });
        // 抽取库区数据
        const zones = res.records.map(item => ({
          value: item.id,
          label: item.zoneName
        }));
        // 更新 zoneId 字段的选项
        updateSchema({
          field: 'zoneId',
          componentProps: {
            options: zones,
            placeholder: '请选择所属库区',
          },
        });
      } catch (error) {
        console.error("获取库区列表失败:", error);
        // 可以在这里更新 UI 提示用户
        updateSchema({
          field: 'zoneId',
          componentProps: {
            options: [],
            placeholder: '加载库区失败',
          },
        });
      }
    } else {
       // 如果没有 warehouseId，清空或设置默认选项
       updateSchema({
          field: 'zoneId',
          componentProps: {
            options: [],
            placeholder: '请先选择所属仓库',
          },
        });
    }
  } else {
     // 新增模式，确保库区选项为空或默认
     updateSchema({
          field: 'zoneId',
          componentProps: {
            options: [],
            placeholder: '请先选择所属仓库',
          },
        });
  }
  // 根据是否显示底部按钮来禁用表单
  setProps({ disabled: !showFooter });
};

// 打开模态框时调用初始化
const handleOpenModal = (data: any) => {
  openModal(true); // 打开模态框
  // 使用 nextTick 确保 DOM 更新后再初始化
  // 或者 useModalInner 内部通常会处理好时机
  // 这里直接调用 initModal 即可，因为 useModalInner 会传入 data
  // 但因为我们直接用了 useModal，需要手动处理
  setTimeout(() => {
    initModal(data);
  }, 0); // 简单的异步处理，确保 modal 已打开
};

// 表单提交处理
const handleSubmit = async () => {
  try {
    const values = await validate(); // 验证表单
    setModalProps({ confirmLoading: true }); // 设置加载状态
    // 调用保存或更新 API
    await saveOrUpdate(values, isUpdate.value);
    // 关闭模态框
    closeModal();
    // 刷新表格
    reload();
    // 触发成功事件 (如果父组件需要监听)
    // emit('success'); 
  } catch (error) {
    console.error('提交表单失败:', error);
    // 可以在这里添加错误提示
  } finally {
    setModalProps({ confirmLoading: false }); // 关闭加载状态
  }
};
// --- 模态框和表单逻辑结束 ---


// 注册table数据
const {
  prefixCls,
  tableContext,
  onExportXls,
  onImportXls
} = useListPage({
  tableProps: {
    title: '储位表',
    api: list,
    columns,
    canResize: false,
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [
      ],
      fieldMapToTime: [
      ],
    },
    actionColumn: {
      width: 120,
      fixed: 'right'
    },
    beforeFetch: (params) => {
      return Object.assign(params, queryParam);
    },
  },
  exportConfig: {
    name: "储位表",
    url: getExportUrl,
    params: queryParam,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess // 复用页面的 handleSuccess
  },
})

const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext

// 高级查询配置
const superQueryConfig = reactive(superQuerySchema);

/**
 * 高级查询事件
 */
function handleSuperQuery(params) {
  Object.keys(params).map((k) => {
    queryParam[k] = params[k];
  });
  reload();
}

/**
 * 新增事件
 */
function handleAdd() {
  handleOpenModal({
    isUpdate: false,
    showFooter: true,
  });
}

/**
 * 编辑事件
 * 修改：传递 record.warehouseId 以便模态框初始化库区选项
 */
function handleEdit(record: Recordable) {
  handleOpenModal({
    record: { ...record }, // 传递完整记录
    isUpdate: true,
    showFooter: true,
  });
}

/**
 * 详情 (如果需要)
 */
function handleDetail(record: Recordable) {
  handleOpenModal({
    record: { ...record },
    isUpdate: true,
    showFooter: false, // 详情模式不显示底部按钮
  });
}

/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}

/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
}

/**
 * 批量启用事件
 */
async function batchEnable() {
  await enableLocation({ ids: selectedRowKeys.value }, handleSuccess);
}

/**
 * 批量禁用事件
 */
async function batchDisable() {
  await disableLocation({ ids: selectedRowKeys.value }, handleSuccess);
}

/**
 * 成功回调 (用于刷新表格和清空选中项)
 */
function handleSuccess() {
  selectedRowKeys.value = []; // 清空选中项
  reload(); // 刷新表格
}

/**
 * 操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
      auth: 'warehouse:wms_storage_locations:edit'
    }
  ]
}

/**
 * 下拉操作栏
 */
function getDropDownAction(record) {
  return [
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    },
    {
      label: record.status === '1' ? '禁用' : '启用',
      // 注意：bind 的参数顺序，API 函数通常期望 (params, successCallback)
      onClick: record.status === '1' ?
        () => disableLocation({ ids: [record.id] }, handleSuccess) :
        () => enableLocation({ ids: [record.id] }, handleSuccess),
      auth: 'warehouse:wms_storage_locations:edit'
    },
    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record),
        placement: 'topLeft',
      },
      auth: 'warehouse:wms_storage_locations:delete'
    }
  ]
}
</script>

<style lang="less" scoped>
:deep(.ant-picker),
:deep(.ant-input-number) {
  width: 100%;
}
</style>



